package com.atguigu.spzx.manager.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.atguigu.spzx.common.exception.GuiguException;
import com.atguigu.spzx.manager.mapper.SysRoleUserMapper;
import com.atguigu.spzx.manager.mapper.SysUserMapper;
import com.atguigu.spzx.manager.service.SysUserService;
import com.atguigu.spzx.model.dto.system.AssginRoleDto;
import com.atguigu.spzx.model.dto.system.LoginDto;
import com.atguigu.spzx.model.dto.system.SysUserDto;
import com.atguigu.spzx.model.entity.system.SysUser;
import com.atguigu.spzx.model.vo.common.ResultCodeEnum;
import com.atguigu.spzx.model.vo.system.LoginVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysRoleUserMapper sysRoleUserMapper;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    //用户登录+获取验证码
    @Override
    public LoginVo login(LoginDto loginDto) {
        // 校验验证码是否正确
        String captcha = loginDto.getCaptcha();     // 用户输入的验证码
        String codeKey = loginDto.getCodeKey();     // redis中验证码的数据key
        // 从Redis中获取验证码
        String redisCode = redisTemplate.opsForValue().get("user:login:validatecode:" + codeKey);
        if(StrUtil.isEmpty(redisCode) || !StrUtil.equalsIgnoreCase(redisCode , captcha)) {
            throw new GuiguException(ResultCodeEnum.VALIDATECODE_ERROR) ;
        }

        // 验证通过删除redis中的验证码
        redisTemplate.delete("user:login:validatecode:" + codeKey) ;

        //根据用户名查询用户
        SysUser sysuer=sysUserMapper.selectByUserName(loginDto.getUserName());
        if(sysuer==null){
            throw new GuiguException(ResultCodeEnum.LOGIN_ERROR);
        }
        //验证密码是否正确
        String inputPassword=loginDto.getPassword();
        String md5InputPassword=DigestUtils.md5DigestAsHex(inputPassword.getBytes());
        //验证密码是否正确
        if(!md5InputPassword.equals(sysuer.getPassword())){
            throw new GuiguException(ResultCodeEnum.LOGIN_ERROR);
        }
        //生成Token令牌，保存数据到redis中
        String token= UUID.randomUUID().toString().replace("-", "");
        redisTemplate.opsForValue().set("user:login:"+token,
                                        JSON.toJSONString(sysuer),
                                        30, TimeUnit.SECONDS);
        //构建响应结果对象
        LoginVo loginvo=new LoginVo();
        loginvo.setToken(token);
        loginvo.setRefresh_token("");

        return loginvo;
    }

    //获取用户信息
    @Override
    public SysUser getUserInfo(String token) {
      String userJson =redisTemplate.opsForValue().get("user:login:" + token);
        return JSON.parseObject(userJson, SysUser.class);
    }
    //退出登录
    @Override
    public void logOut(String token) {
        redisTemplate.delete("user:login:" + token) ;
    }

    //用户分页查询列表
    @Override
    public PageInfo<SysUser> findByPage(SysUserDto sysUserDto, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<SysUser> sysUserList=sysUserMapper.findByPage(sysUserDto);
        PageInfo pageInfo = new PageInfo(sysUserList);
        return pageInfo;
    }

    //用户添加
    @Override
    public void saveSysUser(SysUser sysUser) {
        //首先用户名查重
         SysUser dbSysUser = sysUserMapper.selectByUserName(sysUser.getUserName());
       if(dbSysUser!=null){
          throw  new GuiguException(ResultCodeEnum.USER_NAME_IS_EXISTS);
       }
        //用户密码加密
        sysUser.setPassword(DigestUtils.md5DigestAsHex(sysUser.getPassword().getBytes()));
        //status设置
        sysUser.setStatus(1);
        sysUserMapper.saveSysUser(sysUser);
    }

    //用户修改
    @Override
    public void updateSysUser(SysUser sysUser) {
        sysUserMapper.updateSysUser(sysUser);
    }

    //用户删除
    @Override
    public void deleteById(Long userId) {
        sysUserMapper.deleteById(userId);
    }

    //用户分配角色 保存角色数据
    @Override
    public void doAssign(AssginRoleDto assginRoleDto) {
        // 删除之前的所有的用户所对应的角色数据
        sysRoleUserMapper.deleteByUserId(assginRoleDto.getUserId()) ;

        // 分配新的角色数据
        List<Long> roleIdList = assginRoleDto.getRoleIdList();
        roleIdList.forEach(roleId->{
            sysRoleUserMapper.doAssign(assginRoleDto.getUserId(),roleId);
        });
    }


}
